/**
 * 加速度数据滑动窗口管理器
 * 实现实时数据的滑动窗口效果
 */
class AccelerationWindowManager {
  constructor(options = {}) {
    this.windowSize = options.windowSize || 60; // 窗口大小（数据点数量）
    this.maxDataPoints = options.maxDataPoints || 100; // 最大数据点数
    this.updateInterval = options.updateInterval || 1000; // 更新间隔（毫秒）

    // 数据存储
    this.dataBuffer = new Map(); // 设备数据缓冲区
    this.timeBuffer = []; // 时间轴缓冲区

    // 回调函数
    this.onDataUpdate = options.onDataUpdate || (() => {});
    this.onError = options.onError || (() => {});

    // 状态管理
    this.isRunning = false;
    this.updateTimer = null;

    console.log('AccelerationWindowManager initialized with options:', options);
  }

  /**
   * 启动滑动窗口管理器
   */
  start() {
    if (this.isRunning) {
      console.warn('AccelerationWindowManager is already running');
      return;
    }

    this.isRunning = true;
    this.initializeTimeBuffer();

    console.log('AccelerationWindowManager started');
  }

  /**
   * 停止滑动窗口管理器
   */
  stop() {
    if (!this.isRunning) {
      return;
    }

    this.isRunning = false;

    if (this.updateTimer) {
      clearInterval(this.updateTimer);
      this.updateTimer = null;
    }

    console.log('AccelerationWindowManager stopped');
  }

  /**
   * 初始化时间缓冲区
   */
  initializeTimeBuffer() {
    const now = Date.now();
    this.timeBuffer = [];

    for (let i = this.windowSize - 1; i >= 0; i--) {
      const time = new Date(now - i * this.updateInterval);
      this.timeBuffer.push(time.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }));
    }
  }

  /**
   * 添加新的加速度数据
   * @param {Object} data 加速度数据
   */
  addAccelerationData(data) {
    if (!this.isRunning) {
      console.warn('AccelerationWindowManager is not running');
      return;
    }

    const { deviceId, latheName, accelerationData, timestamp } = data;

    if (!deviceId || !accelerationData) {
      console.warn('Invalid acceleration data:', data);
      return;
    }

    // 获取或创建设备数据缓冲区
    if (!this.dataBuffer.has(deviceId)) {
      this.initializeDeviceBuffer(deviceId, latheName);
    }

    const deviceBuffer = this.dataBuffer.get(deviceId);

    // 添加新数据点
    this.addDataPoint(deviceBuffer, accelerationData, timestamp);

    // 触发数据更新回调
    this.onDataUpdate({
      deviceId,
      latheName,
      data: this.getWindowData(deviceId),
      timestamp
    });
  }

  /**
   * 初始化设备数据缓冲区
   * @param {string} deviceId 设备ID
   * @param {string} latheName 设备名称
   */
  initializeDeviceBuffer(deviceId, latheName) {
    const buffer = {
      deviceId,
      latheName,
      rms: {
        x: new Array(this.windowSize).fill(null),
        y: new Array(this.windowSize).fill(null),
        z: new Array(this.windowSize).fill(null)
      },
      peak: {
        x: new Array(this.windowSize).fill(null),
        y: new Array(this.windowSize).fill(null),
        z: new Array(this.windowSize).fill(null)
      },
      lastUpdate: Date.now()
    };

    this.dataBuffer.set(deviceId, buffer);
    console.log(`Initialized buffer for device ${deviceId} (${latheName})`);
  }

  /**
   * 添加数据点到缓冲区
   * @param {Object} buffer 设备缓冲区
   * @param {Object} data 加速度数据
   * @param {number} timestamp 时间戳
   */
  addDataPoint(buffer, data, timestamp) {
    const now = Date.now();
    const timeSinceLastUpdate = now - (buffer.lastUpdate || 0);

    // 判断是否应该滑动窗口（间隔超过2秒）
    const shouldSlideWindow = timeSinceLastUpdate >= 2000;

    if (shouldSlideWindow) {
      console.log(`📈 滑动窗口管理器: 设备 ${buffer.deviceId} 滑动窗口添加新数据`);

      // 滑动窗口：移除最旧的数据，添加最新的数据
      ['rms', 'peak'].forEach(type => {
        if (data[type]) {
          ['x', 'y', 'z'].forEach(axis => {
            if (data[type][axis] !== undefined) {
              buffer[type][axis].shift(); // 移除最旧的数据
              buffer[type][axis].push(data[type][axis]); // 添加最新的数据
            }
          });
        }
      });

      // 更新时间轴
      this.updateTimeAxis(timestamp);
    } else {
      console.log(`📊 滑动窗口管理器: 设备 ${buffer.deviceId} 更新最新数据点`);

      // 只更新最新数据点，不滑动窗口
      ['rms', 'peak'].forEach(type => {
        if (data[type]) {
          ['x', 'y', 'z'].forEach(axis => {
            if (data[type][axis] !== undefined) {
              const lastIndex = buffer[type][axis].length - 1;
              buffer[type][axis][lastIndex] = data[type][axis]; // 更新最新数据
            }
          });
        }
      });

      // 更新最新时间点
      const time = new Date(timestamp || Date.now());
      const timeString = time.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
      const lastTimeIndex = this.timeBuffer.length - 1;
      this.timeBuffer[lastTimeIndex] = timeString;
    }

    buffer.lastUpdate = timestamp || Date.now();
  }

  /**
   * 更新时间轴
   * @param {number} timestamp 时间戳
   */
  updateTimeAxis(timestamp) {
    const time = new Date(timestamp || Date.now());
    const timeString = time.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });

    this.timeBuffer.shift(); // 移除最旧的时间
    this.timeBuffer.push(timeString); // 添加最新的时间
  }

  /**
   * 获取指定设备的窗口数据
   * @param {string} deviceId 设备ID
   * @returns {Object} 窗口数据
   */
  getWindowData(deviceId) {
    const buffer = this.dataBuffer.get(deviceId);
    if (!buffer) {
      return null;
    }

    return {
      deviceId: buffer.deviceId,
      latheName: buffer.latheName,
      rms: {
        x: [...buffer.rms.x],
        y: [...buffer.rms.y],
        z: [...buffer.rms.z]
      },
      peak: {
        x: [...buffer.peak.x],
        y: [...buffer.peak.y],
        z: [...buffer.peak.z]
      },
      timeData: [...this.timeBuffer],
      lastUpdate: buffer.lastUpdate
    };
  }

  /**
   * 获取所有设备的窗口数据
   * @returns {Map} 所有设备的窗口数据
   */
  getAllWindowData() {
    const result = new Map();

    for (const [deviceId, buffer] of this.dataBuffer) {
      result.set(deviceId, this.getWindowData(deviceId));
    }

    return result;
  }

  /**
   * 清除指定设备的数据
   * @param {string} deviceId 设备ID
   */
  clearDeviceData(deviceId) {
    if (this.dataBuffer.has(deviceId)) {
      this.dataBuffer.delete(deviceId);
      console.log(`Cleared data for device ${deviceId}`);
    }
  }

  /**
   * 清除所有数据
   */
  clearAllData() {
    this.dataBuffer.clear();
    this.initializeTimeBuffer();
    console.log('Cleared all acceleration data');
  }

  /**
   * 获取管理器状态
   * @returns {Object} 状态信息
   */
  getStatus() {
    return {
      isRunning: this.isRunning,
      windowSize: this.windowSize,
      deviceCount: this.dataBuffer.size,
      devices: Array.from(this.dataBuffer.keys()),
      lastUpdate: Math.max(...Array.from(this.dataBuffer.values()).map(b => b.lastUpdate))
    };
  }

  /**
   * 模拟数据（用于测试）
   * @param {string} deviceId 设备ID
   * @param {string} latheName 设备名称
   */
  simulateData(deviceId, latheName) {
    if (!this.isRunning) {
      this.start();
    }

    const generateRandomData = () => ({
      rms: {
        x: Math.random() * 10 + 5,
        y: Math.random() * 10 + 5,
        z: Math.random() * 10 + 5
      },
      peak: {
        x: Math.random() * 20 + 10,
        y: Math.random() * 20 + 10,
        z: Math.random() * 20 + 10
      }
    });

    // 立即添加一个数据点
    this.addAccelerationData({
      deviceId,
      latheName,
      accelerationData: generateRandomData(),
      timestamp: Date.now()
    });

    // 设置定时器持续生成数据
    const simulationTimer = setInterval(() => {
      if (!this.isRunning) {
        clearInterval(simulationTimer);
        return;
      }

      this.addAccelerationData({
        deviceId,
        latheName,
        accelerationData: generateRandomData(),
        timestamp: Date.now()
      });
    }, this.updateInterval);

    console.log(`Started data simulation for device ${deviceId} (${latheName})`);
    return simulationTimer;
  }
}

export default AccelerationWindowManager;
